package com.binguo.helper;


import com.alibaba.druid.support.json.JSONUtils;
import com.binguo.baidu.request.*;
import com.binguo.baidu.response.AddUserVO;
import com.binguo.baidu.response.DelUserVO;
import com.binguo.baidu.response.GetFeatureVO;
import com.binguo.baidu.response.IdentifyVO;
import com.binguo.common.paymodel.MD5Util;
import com.binguo.common.util.Base64Util;
import com.binguo.common.util.JsonUtil;
import com.binguo.entity.face_local.AddFaceResultVO;
import com.binguo.entity.face_local.CreateFaceResultVO;
import com.binguo.entity.face_local.SearchFaceResultDetailVO;
import com.binguo.entity.face_local.SearchFaceResultVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencentcloudapi.iai.v20180301.models.Candidate;
import com.tencentcloudapi.iai.v20180301.models.GetPersonBaseInfoResponse;
import com.tencentcloudapi.iai.v20180301.models.PersonInfo;
import com.tencentcloudapi.iai.v20180301.models.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

// 导入对应产品模块的client
// 导入要请求接口对应的request response类

@Service
public class FaceHelperV6Baidu {
    public static RestTemplate restTemplate = new RestTemplate();
    public static String ipAddress = "192.168.10.88:8080";
    public static Gson gson = (new GsonBuilder()).excludeFieldsWithoutExposeAnnotation().create();

    private static Logger logger = LoggerFactory.getLogger(FaceHelperV6Baidu.class);

    private static String pass = MD5Util.MD5Lower32("123456");

    private static HttpHeaders DEFAULT_JSON_HEADER_UTF8 = new HttpHeaders();
    static {
        DEFAULT_JSON_HEADER_UTF8.setContentType(MediaType.APPLICATION_JSON_UTF8);
    }

    /**
     * 创建人员库
     * @param shopId 传shopId
     * @return true:成功 false失败
     */
    public static boolean isShopExist(String shopId){

        return true;
    }

    /**
     * 创建人员库
     * @param shopId 传shopId
     * @return true:成功 false失败
     */
    public static boolean createGroup(String shopId, String ipAddress){

        return true;
    }

    /**
     * 创建人员
     * personId 为groupId_customerId,确保唯一性
     * @param shopId 传shopId
     * @param personId 传personId
     * @param faceUrl 传人脸图片地址
     * @return faceId
     */
    public static String createPerson(String shopId, String personId, String faceUrl, String ipAddress){

        AddUserForm addUserForm = new AddUserForm();
        addUserForm.setPass(pass);
        addUserForm.setImage_type("URL");
        addUserForm.setImage_content(faceUrl);
//        addUserForm.setImage_content("http://182.254.215.43:8019/images/faces/6ffac775-87b6-4c19-8906-ba7f39a707dc.png");
        addUserForm.setUser_id(personId);
        addUserForm.setUser_info(new UserInfo());
        addUserForm.getUser_info().setName(personId);
//        addUserForm.getUser_info().setPhone_number(personId);
        addUserForm.setAction_type("APPEND");
        addUserForm.setQuality_control("NONE");

        try {
            HttpEntity<String> entity = new HttpEntity<>(JsonUtil.toJson(addUserForm), DEFAULT_JSON_HEADER_UTF8);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://" + ipAddress + "/userManage/addUser", entity, String.class);
            AddUserVO addUserVO = JsonUtil.parse(responseEntity.getBody(), AddUserVO.class);
            if (addUserVO.isCode()) {
                return Base64Util.encode(faceUrl.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

    /**
     * 删除人脸
     * personId 为groupId_customerId,确保唯一性
     * @param personId
     * @param faceId 传创建人脸时返回的faceId值
     * @return true:成功 false:失败
     */
    public static boolean deleteFace(String personId, String faceId, String ipAddress){
        if (!personId.contains("_")) {
            return false;
        }

        DelUserForm delUserForm = new DelUserForm();
        delUserForm.setPass(pass);
        delUserForm.setUser_id(personId);

        try {
            HttpEntity<String> entity = new HttpEntity<>(JsonUtil.toJson(delUserForm), DEFAULT_JSON_HEADER_UTF8);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://" + ipAddress + "/userManage/deleteUserImages", entity, String.class);
            DelUserVO delUserVO = JsonUtil.parse(responseEntity.getBody(), DelUserVO.class);
            if (delUserVO.isCode()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;

    }

    /**
     * 删除人员库
     * personId 为groupId_customerId,确保唯一性
     * @param shopId
     * @return true:成功 false:失败
     */
    public static boolean deleteGroup(String shopId, String ipAddress){


        return false;
    }

    /**
     * 删除人员(在不知道人员所属商户的情况下使用此方法)
     * personId 为groupId_customerId,确保唯一性
     * @param personId
     * @return true:成功 false:失败
     */
    public static boolean deletePerson(String personId, String ipAddress){
        if (!personId.contains("_")) {
            return false;
        }

        DelUserForm delUserForm = new DelUserForm();
        delUserForm.setUser_id(personId);
        delUserForm.setPass(pass);

        try {
            HttpEntity<String> entity = new HttpEntity<>(JsonUtil.toJson(delUserForm), DEFAULT_JSON_HEADER_UTF8);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://" + ipAddress + "/userManage/deleteUser", entity, String.class);
            DelUserVO delUserVO = JsonUtil.parse(responseEntity.getBody(), DelUserVO.class);
            if (delUserVO.isCode()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 人员库删除人员
     * personId 为groupId_customerId,确保唯一性
     * @param shopId
     * @param personId
     * @return true:成功 false:失败
     */
    public static boolean deletePersonFromShop(String shopId, String personId, String ipAddress){

        return deletePerson(personId, ipAddress);
    }

    /**
     * 获取人员基础信息
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @return GetPersonBaseInfoResponse
     */
    public static GetPersonBaseInfoResponse getPersonBaseInfo(String customerId, String ipAddress){


        return null;
    }

    /**
     * 获取人员列表
     * personId 为groupId_customerId,确保唯一性
     * @param shopId
     * @param offset 第几个结果集开始查
     * @param limit 查询多少个
     * @return faceId
     */
    public static PersonInfo[] getPersonList(String shopId, Integer offset, Integer limit, String ipAddress){

        return null;

    }

    /**
     * 人脸搜索
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrl
     * @param shopId
     * @return 查询结果集
     */
    public static Result[] searchFacesFromSingleShop(String faceUrl, String shopId, String ipAddress){
        return searchFacesFromMultiple(faceUrl, new String[]{shopId}, ipAddress);
    }

    /**
     * 人脸搜索
     * @param faceUrl
     * @param shopId
     * @return 查询结果集
     */
    public static Result[] searchFacesFromMultiple(String faceUrl, String[] shopId, String ipAddress){

        IdentifyForm identifyForm = new IdentifyForm();
        identifyForm.setPass(pass);
        identifyForm.setImage_type("URL");
        identifyForm.setUser_num(1);
        identifyForm.setImage_content(faceUrl);

        try {
            HttpEntity<String> entity = new HttpEntity<>(JsonUtil.toJson(identifyForm), DEFAULT_JSON_HEADER_UTF8);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://" + ipAddress + "/recognitionManage/identify", entity, String.class);
            IdentifyVO identifyVO = JsonUtil.parse(responseEntity.getBody(), IdentifyVO.class);

            if (identifyVO.isCode()) {
                Result[] results = new Result[1];

                Result tempResult = new Result();

                Candidate candidate = new Candidate();
                candidate.setFaceId(null);
                candidate.setPersonId(identifyVO.getUser_list().get(0).getUser_id());
                candidate.setScore(new Float(100));

                Candidate tempCandidate[] = new Candidate[1];
                tempCandidate[0] = candidate;
                tempResult.setCandidates(tempCandidate);
                results[0] = tempResult;
                return results;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 人脸检测与分析
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrl
     * @return 人脸图片质量分
     */
    public static int detectFace(Integer shopId, String faceUrl, String ipAddress){

        GetFeatureForm getFeatureForm = new GetFeatureForm();
        getFeatureForm.setPass(pass);
        getFeatureForm.setImage_type("URL");
        getFeatureForm.setImage_content(faceUrl);
        try {
            HttpEntity<String> entity = new HttpEntity<>(JsonUtil.toJson(getFeatureForm), DEFAULT_JSON_HEADER_UTF8);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://" + ipAddress + "/recognitionManage/getFeature", entity, String.class);
            GetFeatureVO getFeatureVO = JsonUtil.parse(responseEntity.getBody(), GetFeatureVO.class);

            if (getFeatureVO.isCode()) {
                return 100;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 0;

    }

    /**
     * 人脸比对
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrlSource
     * @param faceUrlTarget
     * @return 对比分数
     */
    public static float compareFace(String faceUrlSource, String faceUrlTarget, String ipAddress){

        return 0;

    }

    /**
     * 人脸静态活体检测
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrl
     * @return 检测结果分数
     */
    public static float detectLiveFace(String faceUrl, String ipAddress){



        return 0;
    }

    /**
     * 人脸验证
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @param faceUrl
     * @return true:匹配 false:不匹配
     */
    public static boolean VerifyFace(String customerId, String faceUrl, String ipAddress){

        return false;

    }

    /**
     * 增加人脸
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @param faceUrl
     * @return true:成功 false:失败
     */
    public static String addFace(String customerId, String faceUrl, String ipAddress){
        return createPerson("", customerId, faceUrl, ipAddress);
    }


    public static void main(String[] args) {
        String s = "a_b_c";
        System.out.println(s.split("_").length);
    }

}
